// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
/**
 * 插件前台控制器
 * 如果插件有前台展示业务，写在这个控制器里面
 * 插件如需建立表务必遵循下面格式：
 * 单表：表前缀_ext_插件目录名
 * 多表：表前缀_ext_插件目录名，表前缀_ext_插件目录名_分表1，表前缀_ext_插件目录名_分表2...
 */
const fs = require('fs')
module.exports = class extends think.cmswing.extIndex {
  /**
   * index action
   *
   * @return {Promise} []
   */

  async indexAction() {
    // 检测是否开启微博登陆
    if (Number(this.config('ext.weixin.is')) === 0) {
      const error = this.controller('cmswing/error')
      return error.noAction('没有开启微信扫码登陆，请到后台开启！')
    }
    // 检测是否登陆
    if (this.is_login) {
      return this.redirect('/center/index')
    }
    const host = this.ctx.host
    const redirectURI = `https://${host}/ext/weixin/index/index`
    // 检查是否回掉code，如果没有跳转授权接口
    if (think.isEmpty(this.get('code'))) {
      const appid = this.config('ext.weixin.appid')
      const url = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${encodeURIComponent(
        redirectURI
      )}&response_type=code&scope=snsapi_login&state=weblogin#wechat_redirect`
      return this.redirect(url)
    } else {
      const code = this.get('code')
      const state = this.get('state')
      const weixin = this.extService('weixin', 'weixin', code, state)
      const token = await weixin.gettoken()
      // console.log(token);
      // 获取access token
      const wxUser = await this.model('ext_weixin').where({ openid: token.openid }).find()
      if (think.isEmpty(wxUser)) {
        // 创建
        await this.model('ext_weixin').add(token)
      } else {
        // 更新
        await this.model('ext_weixin')
          .where({
            openid: token.openid
          })
          .update(token)
      }
      // 获取用户信息
      const userinfo = await weixin.getuserinfo(token.access_token, token.openid)
      await this.model('ext_weixin')
        .where({
          openid: userinfo.openid
        })
        .update(userinfo)
      // 检查微信号是否跟网站会员绑定
      if (think.isEmpty(wxUser.uid) || wxUser.uid == 0) {
        // 没绑定跳转绑定页面
        return this.redirect(`/ext/weixin/index/login/?openid=${userinfo.openid}`)
      } else {
        // 绑定直接登陆
        const last_login_time = await this.model('member').where({ id: wxUser.uid }).getField('last_login_time', true)
        const weixinUserInfo = {
          uid: wxUser.uid,
          username: wxUser.nickname,
          last_login_time: last_login_time
        }
        await this.session('webuser', weixinUserInfo)
        await this.model('cmswing/member').autoLogin({ id: wxUser.uid }, this.ip) // 更新用户登录信息，自动登陆
        return this.redirect('/center/index')
      }
    }
  }

  // 用户绑定页面
  async loginAction() {
    if (Number(this.config('ext.weixin.is')) === 0) {
      const error = this.controller('common/error')
      return error.noAction('没有开启微信扫码登陆，请到后台开启！')
    }
    if (this.is_login) {
      return this.redirect('/center/index')
    }
    const openid = this.get('openid')
    const wxUser = await this.model('ext_weixin').where({ openid: openid }).find()
    console.log(wxUser)
    this.assign('wx_user', wxUser)
    this.meta_title = '账号绑定'
    return this.isMobile ? this.extDisplay('m') : this.extDisplay()
  }

  /** 完善资料绑定 */
  async organizingAction() {
    const data = this.post()
    // 验证
    let res
    if (think.isEmpty(data.username)) {
      return this.fail('用户昵称不能为空！')
    } else {
      res = await this.model('member').where({ username: ltrim(data.username) }).find()
      if (!think.isEmpty(res)) {
        return this.fail('用户昵称已存在，请重新填写！')
      }
    }
    if (think.isEmpty(data.mobile)) {
      return this.fail('手机号码不能为空！')
    } else {
      res = await this.model('member').where({ mobile: data.mobile }).find()
      if (!think.isEmpty(res)) {
        return this.fail('手机号码已存在，请重新填写！')
      }
    }
    if (think.isEmpty(data.email)) {
      return this.fail('电子邮箱不能为空！')
    } else {
      res = await this.model('member').where({ email: data.email }).find()
      if (!think.isEmpty(res)) {
        return this.fail('电子邮箱已存在，请重新填写！')
      }
    }
    if (think.isEmpty(data.password) && think.isEmpty(data.password2)) {
      return this.fail('密码不能为空！')
    } else {
      if (data.password != data.password2) {
        return this.fail('两次输入的密码不一致，请重新填写！')
      }
    }
    data.status = 1
    data.reg_time = new Date().valueOf()
    data.reg_ip = _ip2int(this.ip)
    data.password = encryptPassword(data.password)
    const reg = await this.model('member').add(data)
    if (!think.isEmpty(reg)) {
      // 添加用户副表
      await this.model('ext_weixin').where({ openid: data.openid }).update({ uid: reg })
      // 更新微信头像
      // const filePath = think.resource + '/upload/avatar/' + reg
      // think.mkdir(filePath)
      // if (!think.isFile(filePath + '/avatar.png')) {
      //   await this.spiderImage(data.headimgurl, filePath + '/avatar.png')
      // }
    }
    // console.log(data);
    await this.model('cmswing/member').autoLogin({ id: reg }, this.ip) // 更新用户登录信息，自动登陆
    const wxUserInfo = {
      uid: reg,
      username: data.username,
      last_login_time: data.reg_time
    }
    await this.session('webuser', wxUserInfo)
    return this.success({ name: '绑定成功', url: '/center/index' })
  }
  /** 登录绑定 */
  async logonbindingAction() {
    const data = this.post()
    // console.log(data);
    const username = this.post('username')
    let password = this.post('password')
    password = encryptPassword(password)
    // console.log(data);

    const res = await this.model('cmswing/member').signin(username, password, this.ip, 5, 0)
    // console.log(res);
    if (res.uid > 0) {
      // 记录用户登录行为
      // await this.model("action", {}, "admin").log("user_login", "member", res.uid, res.uid, this.ip(), this.http.url);
      // console.log(11111111111111);
      const wxInfo = await this.model('ext_weixin').where({ openid: data.openid }).find()
      // console.log(wxInfo);
      await this.model('ext_weixin').where({ openid: data.openid }).update({ uid: res.uid })
      // 更新微信头像
      // const filePath = think.resource + '/upload/avatar/' + res.uid
      // think.mkdir(filePath)
      // if (!think.isFile(filePath + '/avatar.png')) {
      //   await this.spiderImage(data.headimgurl, filePath + '/avatar.png')
      // }
      res.username = wxInfo.nickname
      await this.session('webuser', res)
      // TODO 用户密钥
      return this.success({ name: '绑定成功', url: '/center/index' })
    } else {
      // 登录失败
      let fail
      switch (res) {
        case -1:
          fail = '用户不存在或被禁用'
          break // 系统级别禁用
        case -2:
          fail = '密码错误'
          break
        default:
          fail = '未知错误'
          break // 0-接口参数错误（调试阶段使用）
      }
      return this.fail(fail)
    }
  }
}
